package com.magic.gre.mvp.presenter;

import android.renderscript.BaseObj;
import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.magic.gre.entity.UserBean;
import com.magic.gre.entity.base.BaseObjectModel;
import com.magic.gre.helper.Apphelper;
import com.magic.gre.mvp.contract.WXEntryContract;
import com.magic.gre.mvp.model.WXEntryModelImpl;
import com.noname.lib_base_java.mvp.BasePresenterImpl;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Author: Lmoumou
 * Date: 2019-01-31 16:29
 * 文件名: WXEntryPresenterImpl
 * 描述:
 */
public class WXEntryPresenterImpl extends BasePresenterImpl<WXEntryContract.View, WXEntryContract.Model>
        implements WXEntryContract.Presenter {
    public WXEntryPresenterImpl(WXEntryContract.View view) {
        super(view);
    }

    @Override
    protected WXEntryContract.Model creatModel() {
        return new WXEntryModelImpl();
    }


    @Override
    public void pAccessToken(String url, Map<String, Object> parms) {
        mModel.mAccessToken(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String string = responseBody.string();
                    if (TextUtils.isEmpty(string)) {
                        mView.doPrompt("数据错误");
                        return;
                    }
                    JSONObject jsonObject = new JSONObject(string);
                    mView.vAccessToken(jsonObject.getString("access_token"), jsonObject.getString("openid"));

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        }, url, parms);
    }

    @Override
    public void pWxLogin(final String openid) {
        mModel.mWxLogin(new CommonObserver<BaseObjectModel<UserBean>>(new TypeToken<BaseObjectModel<UserBean>>(){}.getType()) {
            @Override
            protected void onSuccess(BaseObjectModel<UserBean> baseObjectModel) {
                Apphelper.putUserInfo(baseObjectModel.body);
                Apphelper.putToken(baseObjectModel.body.getToken());
                mView.vWxLoginSuc();
            }

            @Override
            public void onError(int status, String msg) {
                mView.vWxLoginFail(status,openid,msg);
            }
        }, openid);
    }
}
